package com.slj.cloudaibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.slj.cloudaibaba.entity.PayEntity;
import com.slj.cloudaibaba.model.response.Result;
import com.slj.cloudaibaba.model.response.ResultCode;
import com.slj.cloudaibaba.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController {
    @Value("${server.port}")
    private String port;

    @Autowired
    private PayService payService;

    @GetMapping("/port/{id}")
    @SentinelResource(value = "payResource", blockHandler = "blockHandler", fallback = "fallback")
    public Result<String> port(@PathVariable("id") Integer id) {
        if (id.equals(5)) {
            throw new RuntimeException("error");
        }
        return Result.success(port);
    }

    @GetMapping("")
    public Result<List<PayEntity>> findAll() {
        return Result.success(payService.findAll());
    }

    @PostMapping("")
    public Result<Void> save(@RequestBody PayEntity payEntity) {
        payService.save(payEntity);
        return Result.success(null);
    }

    public Result<String> blockHandler(@PathVariable Integer id, BlockException e) {
        log.info("=============================");
        log.error(e.getMessage());
        return Result.error(ResultCode.BAD_REQUEST);
    }
}
